<template>
  <div>
    <el-row class="layout-search">
      <el-input
        :prefix-icon="Search"
        :placeholder="$t('message.searchTemp')"
      ></el-input>
    </el-row>
    <el-tabs v-model="activeTemplate" class="layout-tabs">
      <el-tab-pane :label="$t('message.recommendTemp')" name="data">
        <div class="layout-templates" @scroll="handleScroll" ref="templateRef">
          <div v-for="(item, index) in templateItems" :key="item.id" class="thumbnail">
            <img :src="item.preview + '?x-oss-process=style/img_tum'" alt="" :ref="(e) => setItemStyle(e, index)" @click="handleChangeTemplate(item)"/>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane :label="$t('message.myTemp')" name="self">
        <el-radio-group v-model="activeSelfTemplate" size="small" class="full-ratio">
          <!-- <el-radio-button value="buy" :label="$t('message.myPurchases')" /> -->
          <el-radio-button value="collect" :label="$t('message.myFavorites')" />
        </el-radio-group>
      </el-tab-pane>
      <el-tab-pane :label="$t('message.teamTemp')" name="team">{{ $t("message.teamTemp") }}</el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { vue, axios} from '@core';
const { ref,onMounted, computed } = vue;
import { Search } from "@element-plus/icons-vue"
import restPath  from '@views/fabric/api/template'

import { useTemplatesStore } from '@views/fabric/store'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { unzip } from "@views/fabric/utils/crypto"
import { PageSize } from "@views/fabric/configs/size"
import { throttle, debounce } from 'lodash-es'

const templatesStore = useTemplatesStore()
const templateItems = ref([])
const activeTemplate = ref("data");
const activeSelfTemplate = ref("buy");
// const images = ref([])
const page = ref(1)
const totalPage = ref(1)
const templateRef = ref()

const setItemStyle = (img, index) => {
  if (!img) return;
  const update = () => {
    const item = img.parentElement;
    if (!item) return;
    const gapRows = index >= 2 ? 2 : 0;
    const rows = Math.ceil(item.clientHeight / 2) + gapRows;
    item.style.gridRowEnd = `span ${rows}`;
  }
  update();
  img.onload = update;
  img.onerror = function() {
    img.src = require(`/static/images/loading.gif`).default;
    update();
  };
}

const handleScroll = debounce(async () => {
  const mainElement = templateRef.value
  const scrollHeight = mainElement.scrollHeight, scrollTop = mainElement.scrollTop, clientHeight = mainElement.clientHeight
  if (scrollHeight - (scrollTop + clientHeight) <= 200) {
    if (page.value < totalPage.value) {
      page.value += 1
      await getTemplateItems()
    }
  }
}, 300)

const loadTemplateImage = () => {
  templateItems.value.forEach(item => {
    const itemImages = item.images
    if (itemImages && JSON.parse(itemImages)) {
      const images = JSON.parse(itemImages)
      images.forEach(ele => {
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.src = ele
        img.onerror = function() {
          img.src = require(`/static/images/loading.gif`).default;
        };
      })
    }
  })
}

const getTemplateItems = () => {
  const pageParams = { page: page.value, size: PageSize }
  axios
      .get(restPath.template.getTemplateDetailPages,{params:pageParams}).then((res) => {
        if (res.data && res.data.code === 200) {
          page.value = res.data.data.page
          totalPage.value = res.data.data.total_pages
          templateItems.value = templateItems.value.concat(res.data.data.items)
          loadTemplateImage()
        }
      }).catch((e) => {
        console.log("查询出错：" + e);
      });
  
}

const handleChangeTemplate = (item) => {
  ElMessageBox.confirm(
    '是否确认更换模板？',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(async () => {
      const templateData = unzip(item.data)
      const data = JSON.parse(templateData)
      console.log('data:', data)
      const loadingInstance = ElLoading.service({ fullscreen: true, background: 'rgba(122, 122, 122, 0.5)' })
      await templatesStore.changeTemplate(data)
      nextTick(() => loadingInstance.close())
      ElMessage({
        type: 'success',
        message: '更换模板成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'error',
        message: '模板加载失败,请联系管理员修改bug了',
      })
    })
  
}

onMounted(async () => {
  await getTemplateItems()
})
</script>

<style lang="scss" scoped>
:deep(.el-tabs__item) {
  padding: 0;
}
.layout-search {
  margin: 0 auto;
  width: 80%;
  padding: 10px;
  height:44px;
}
.layout-tabs {
  width: 90%;
  margin: 0 auto;
  height:calc(100% - 44px);
  position:relative;
  :deep(.el-tabs__content){
    height:calc(100% - 55px);
    overflow:hidden;
    .el-tab-pane{
      height:100%;
      position:relative;
      overflow:auto;
    }
  }
}
.layout-templates {
  flex-wrap: wrap;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 2px 0;
  padding-bottom: 20px;
  align-items: start;
  .thumbnail {
    padding: 2px 0;
  }
  .thumbnail img {
    outline: 1px solid $borderColor;
    width: 124px;
    margin: 0 5px;
    cursor: pointer;
    &:hover {
      outline-color: $themeColor;
    }
  }
}
.full-ratio {
  display: flex;
  flex: 1;
  .el-radio-button {
    width: 50%;
  }
  .el-radio-button__inner {
    width: 100%;
  }
}
:deep(.full-ratio .el-radio-button__inner) {
  width: 100%;
}
</style>
<style>
.layout-tabs .el-tabs__nav {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-around;
  width: 100%;
}
</style>